import React, {Component} from 'react'
import {
  NavBar,
  InputItem,
  Button,
  WingBlank,
  List,
  WhiteSpace,
} from 'antd-mobile'
import {connect} from 'react-redux'
import {Redirect} from 'react-router-dom'

import Logo from '../../components/logo/logo'
import {login} from "../../redux/actions";

class Login extends Component {

  state = {
    username: '',
    password: '',
  };

  login = () => {
    this.props.login(this.state);
  };

  handleChange = (name, val) => {
    // 更新对应状态
    this.setState({
      [name]: val
    })
  };

  toRegister = () => {
    this.props.history.replace('/register')
  };

  render() {
    const {msg,redirectTo} = this.props.user;
    // 如果redirectTo有值，就需要重定向到指定的路由
    if(redirectTo){
      return <Redirect to={redirectTo}/>
    }

    return (
        <div>
          <NavBar>硅谷直聘</NavBar>
          <Logo/>
          <WingBlank>
            <List>
              {msg? <div className="error-msg">{msg}</div> : null}
              <WhiteSpace/>
              <InputItem placeholder="用户名" onChange={val => {
                this.handleChange('username', val)
              }}>用户名:</InputItem>
              <WhiteSpace/>
              <InputItem type="password" placeholder="密码" onChange={val => {
                this.handleChange('password', val)
              }}>密&nbsp;&nbsp;&nbsp;码:</InputItem>
              <WhiteSpace/>
              <Button type="primary" onClick={this.login}>登录</Button>
              <Button onClick={this.toRegister}>还没有账户</Button>
            </List>
          </WingBlank>
        </div>
    )
  }
}

export default connect(
    state => ({user:state.user}),
    {login}
)(Login)